package com.aerozhonghuan.logisticsmall.framework.hybrid;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;

import com.aerozhonghuan.logisticsmall.framework.base.TitlebarFragment;
import com.aerozhonghuan.logisticsmall.framework.hybrid.bean.JsNotificationEvent;
import com.aerozhonghuan.logisticsmall.utils.NetUtils;
import com.aerozhonghuan.logisticsmall.widget.ErrorView;
import com.aerozhonghuan.foundation.eventbus.EventBusManager;
import com.aerozhonghuan.foundation.log.LogUtil;
import com.aerozhonghuan.hybrid.SimpleInjectJsMobileAgent;
import com.aerozhonghuan.hybrid.XJsCallback;
import com.aerozhonghuan.hybrid.XWebView;
import com.aerozhonghuan.hybrid.XWebViewListener;
import com.aerozhonghuan.hybrid.actionhandler.OnReceiveMessageListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * web页面的 fragment
 */
public class NewWebviewFragment extends TitlebarFragment {
    private static final String TAG = NewWebviewFragment.class.getSimpleName();
    public static final String KEY_PARAM_URL = "url";
    public static final String KEY_PARAM_TITLE = "title";
    public static final String KEY_PARAM_NEEDHARDWARE = "isNeedHardWare";
    public static final int REQUEST_CODE = 1010;

    private ViewGroup rootView;
    private XWebView mWebView;
    private String url;
    private SimpleInjectJsMobileAgent theMobileAgent;
    private List<SimpleActionHandler> simpleActionHandlers;
    private ErrorView errorView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusManager.register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            mWebView = new XWebView(getContext(), null, true);
            initWebView();
            initDataAndLoad();
        }
        return rootView;
    }

    /**
     * 配置webview
     */
    private void initWebView() {
        //没有网络则优先读取本地缓存
        boolean networkConnected = NetUtils.isConnected(getContext());
        if (!networkConnected) {
            mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        rootView = new FrameLayout(getContext());
        rootView.addView(mWebView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
        //配置 注入js代理对象
        theMobileAgent = onConfigMobildAgentObject();
        if (theMobileAgent != null) {
            mWebView.addMobileAgentObject(theMobileAgent, "mobileAgent");
        }
        mWebView.setWebViewListerner(onInitWebviewListener());
        mWebView.setWebChromeClient(mWebView.new WebChromeClient() {
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                LogUtil.d("ssss", String.format("url:%s   message:%s result:%s", url, message, result));
                // TODO: 2019/1/17 自定义弹窗
                return true;
            }
        });
    }

    /**
     * 初始化数据并加载页面
     */
    private void initDataAndLoad() {
        //配置指定的url,如果未指定，则不加载
        String tmpUrl = null;
        if (getArguments() != null) {
            tmpUrl = getArguments().getString(KEY_PARAM_URL);
            if (!TextUtils.isEmpty(tmpUrl)) {
                url = tmpUrl;
            }
            //title
            String title = getArguments().getString(KEY_PARAM_TITLE);
            if (!TextUtils.isEmpty(title)) {
                getTitlebar().setTitle(title);
            }

            if (getArguments().containsKey(KEY_PARAM_NEEDHARDWARE) && getArguments().getBoolean(KEY_PARAM_NEEDHARDWARE)) {
                mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            }
        }
        // onConfigURL级别高于getArgument
        tmpUrl = onConfigURL(getArguments());
        if (!TextUtils.isEmpty(tmpUrl)) {
            url = tmpUrl;
        }
        if (!TextUtils.isEmpty(url)) {
            mWebView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl(url);
                }
            }, 100);
        }
    }

    /**
     * 创建 MobildAgentObject
     *
     * @return
     */
    protected SimpleInjectJsMobileAgent onConfigMobildAgentObject() {
        SimpleInjectJsMobileAgent simpleInjectJsMobileAgent = new SimpleInjectJsMobileAgent();
        simpleInjectJsMobileAgent.setOnReceiveMessageListener(new OnReceiveMessageListener() {
            @Override
            public void onReceiveMessageFromJs(@NonNull String action, @Nullable JSONObject params, @Nullable XJsCallback callBack) {
                if (simpleActionHandlers == null) {
                    simpleActionHandlers = new ArrayList<>();
                } else {
                    for (SimpleActionHandler handler :
                            simpleActionHandlers) {
                        if (TextUtils.equals(action, handler.getAction())) {
                            handler.handlAction(action, params, callBack, params == null ? "":params.toString());
                            return;
                        }
                    }
                }
                LogUtil.d(TAG, "没有加载过::"+action);
                SimpleActionHandler simpleActionHandler = createActionHandler(action);
                if (simpleActionHandler != null) {
                    simpleActionHandler.handlAction(action, params, callBack, params == null ? "":params.toString());
                    simpleActionHandlers.add(simpleActionHandler);
                }
            }
        });
        return simpleInjectJsMobileAgent;
    }

    public SimpleActionHandler createActionHandler(String action){
        return JsMobileAgentFactory.createActionHandler(action, NewWebviewFragment.this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (simpleActionHandlers != null) {
            for (SimpleActionHandler handler : simpleActionHandlers) {
                handler.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    @SuppressWarnings("unused")
    public void onEvent(JsNotificationEvent jsNotificationEvent) {
        if (getActivity().isFinishing()) {
            return;
        }
        getWebView().invokeJsScript(String.format("hybrid.raiseEvent(\"%s\", %s)", jsNotificationEvent.getEvent(), jsNotificationEvent.getData()));
    }

    /**
     * 当 初始化一些callback
     * @return
     */
    @NonNull
    protected XWebViewListener onInitWebviewListener() {
        return new XWebViewListener() {
            @Override
            public void onReceiveError(int errorCode, String description, String failingUrl) {
                LogUtil.i(TAG, "onReceiveError");
                showErrorView();
            }

            @Override
            public void onReceiveTitle(String title) {
                super.onReceiveTitle(title);
                LogUtil.d(TAG,"onReceiveTitle");

            }

            @Override
            public void onPageFinished(String url) {
                super.onPageFinished(url);
                LogUtil.d(TAG,"onPageFinished");
                // TODO: 2019/1/26 android 4.4一下获取不到js方法返回值,只能通过js调用原生方法来获取
                getWebView().invokeJsScript("getNavBarRightButtonsConfigure()");
            }

            @Override
            public void onPageStarted(String url) {
                super.onPageStarted(url);
                LogUtil.d(TAG,"onPageStarted");
                setUrl(url);
                if (isShowingErrorView()) {
                    showWebViewVisible();
                }
            }
        };
    }

    /**
     * 配置要显示的url, 可以不进行配置,通过argument直接传输,但是此方法级别要比argument高
     * @param bundle
     */
    protected String onConfigURL(Bundle bundle) {
        return null;
    }

    public void showErrorView() {
        runOnUI(new Runnable() {
            @Override
            public void run() {
                if (errorView == null) {
                    errorView = onCreateErrorView();
                    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
                    rootView.addView(errorView, params);
                }
                mWebView.setVisibility(View.GONE);
                errorView.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 当创建errorview 时
     *
     * @return
     */
    protected ErrorView onCreateErrorView() {
        ErrorView errorView1 = new ErrorView(getContext());
        errorView1.setNoNetworkState();
        errorView1.setOnConfirmButtonClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissErrorView();
                mWebView.loadUrl(url);
            }
        });
        return errorView1;
    }

    protected void dismissErrorView() {
        if (errorView == null) {
            return;
        }
        errorView.setVisibility(View.GONE);
        mWebView.setVisibility(View.VISIBLE);
    }

    public ErrorView getErrorView() {
        return errorView;
    }

    /**
     * errorview 是否可见
     *
     * @return
     */
    protected boolean isShowingErrorView() {
        return errorView != null && errorView.getVisibility() == View.VISIBLE;
    }

    /**
     * 让 webview可见
     */
    protected void showWebViewVisible() {
        mWebView.setVisibility(View.VISIBLE);
        errorView.setVisibility(View.GONE);
    }

    /**
     * 由于fragment不能直接控制onkeydown事件,需要借由activity控制,此方法会被activity调用
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView == null || "about:blank".equals(mWebView.getUrl()) || mWebView.canGoBack()) {
                mWebView.goBack();//返回上一页面
                return true;
            } else {
                if (getActivity() != null && !getActivity().isFinishing()) {
                    getActivity().finish();
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 在UI线程执行
     *
     * @param runnable
     */
    protected void runOnUI(Runnable runnable) {
        if (getActivity() == null || getActivity().isFinishing()) {
            return;
        }
        if (rootView == null) {
            return;
        }
        rootView.post(runnable);
    }

    /**
     * 动态更改当前加载url
     */
    protected void loadURL(String url1) {
        LogUtil.d(TAG, "loadURL ulr=" + url1);
        setUrl(url1);
        if (TextUtils.isEmpty(getUrl())) {
            mWebView.loadUrl(XWebView.ABOUT_BLANK);
            return;
        }
        mWebView.loadUrl(getUrl());
    }

    public XWebView getWebView() {
        return mWebView;
    }

    /**
     * 获得 上次的 url
     * @return
     */
    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public void onDestroy() {
        EventBusManager.unregister(this);
        if (mWebView != null) {
            mWebView.destroy();
            mWebView = null;
        }
        if (rootView != null) {
            rootView = null;
        }
        if (theMobileAgent != null) {
            theMobileAgent.release();
            theMobileAgent = null;
        }
        super.onDestroy();
    }
}
